package controllers

import (
	"encoding/json"
	"os/exec"

	"cve-agency-manager/common"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
)

type TriggerTrackController struct {
	beego.Controller
}

func (c *TriggerTrackController) RetData(resp map[string]interface{}) {
	c.Data["json"] = resp
	c.ServeJSON()
}

type CveReqPramData struct {
	CveNum       string `json:"cveNum"`
	PackName     string `json:"packName"`
	PackVersion  string `json:"packVersion"`
	IssueNumber  string `json:"issueNumber"`
	AffectBranch string `json:"affectBranch"`
	CveUrl       string `json:"cveUrl"`
	PatchUrl     string `json:"patchUrl"`
	Verify       bool   `json:"verify"`
}

// @Title TriggerTrack
// @Description Trigger Track
// @Param body body models.TriggerTrack	true
// @Success 200 {int} models.Id
// @Failure 403 body is empty
// @router / [post]
func (c *TriggerTrackController) Post() {
	var cvePram CveReqPramData
	req := c.Ctx.Request
	addr := req.RemoteAddr
	logs.Info("Method: ", req.Method, "Client request ip address: ", addr, ",Header: ", req.Header)
	resp := make(map[string]interface{})
	resp["errno"] = common.RecodeParamErr
	resp["errmsg"] = common.RecodeText(common.RecodeParamErr)
	defer c.RetData(resp)
	json.Unmarshal(c.Ctx.Input.RequestBody, &cvePram)
	logs.Info("trigger track request parameters: ", string(c.Ctx.Input.RequestBody))
	// Call python script
	pythonFile := beego.AppConfig.String("python_conf::python_file")
	args := []string{}
	if !cvePram.Verify {
		if len(cvePram.CveUrl) > 1 || len(cvePram.PatchUrl) > 1 {
			args = []string{pythonFile, "feedback", "-c", cvePram.CveNum, "-p", cvePram.CveUrl, "-u", cvePram.PatchUrl}
		} else {
			args = []string{pythonFile, "comment", "-c", cvePram.CveNum, "-r", cvePram.PackName, "-i", cvePram.IssueNumber}
		}
	} else {
		args = []string{pythonFile, "find_adaptive_patch", "-c", cvePram.CveNum, "-r", cvePram.PackName, "-p", "-i", cvePram.IssueNumber}
	}
	//args := []string{pythonFile}
	out, err := exec.Command("python3", args...).Output()
	if err != nil {
		logs.Error("cmd python3 ==> python ", args, ",err: ", err)
		resp["errno"] = common.RecodeCmdFailed
		resp["errmsg"] = common.RecodeText(common.RecodeCmdFailed)
		return
	}
	logs.Info("out: ", string(out))
	resp["errno"] = common.RecodeOk
	resp["errmsg"] = common.RecodeText(common.RecodeOk)
	return
}
